<template>
  <Modal
    :open="visible"
    title="编辑聊天室"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <Form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
    >
      <FormItem
        label="聊天室名称"
        name="name"
      >
        <Input
          v-model:value="formData.name"
          placeholder="请输入聊天室名称"
          :maxlength="100"
        />
      </FormItem>

      <FormItem
        label="聊天室描述"
        name="description"
      >
        <TextArea
          v-model:value="formData.description"
          placeholder="请输入聊天室描述（可选）"
          :rows="3"
          :maxlength="500"
          show-count
        />
      </FormItem>

      <FormItem
        label="自动对话"
        name="autoTalkEnabled"
      >
        <Switch
          v-model:checked="formData.autoTalkEnabled"
          checked-children="开启"
          un-checked-children="关闭"
        />
        <div class="form-help">开启后，AI角色将自动参与对话</div>
      </FormItem>
    </Form>
  </Modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { Modal, Form, FormItem, Input, Switch, message } from 'ant-design-vue'
import type { FormInstance, Rule } from 'ant-design-vue/es/form'
import { Codewin } from '@/api/generated/Codewin'
import { useAuthStore } from '@/stores/modules/auth'
import type { UpdateChatRoomRequest } from '@/api/generated/data-contracts'

const { TextArea } = Input

interface Props {
  visible: boolean
  roomData?: {
    id: string
    name: string
    description?: string
    autoTalkEnabled?: number
  }
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const authStore = useAuthStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

const formData = reactive({
  name: '',
  description: '',
  autoTalkEnabled: true
})

const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: '请输入聊天室名称', trigger: 'blur' },
    { min: 1, max: 100, message: '聊天室名称长度为1-100个字符', trigger: 'blur' }
  ]
}

// 监听props变化，更新表单数据
watch(() => props.roomData, (newData) => {
  if (newData) {
    formData.name = newData.name
    formData.description = newData.description || ''
    formData.autoTalkEnabled = newData.autoTalkEnabled === 1
  }
}, { immediate: true })

// 创建API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'https://www.codewin.top',
  securityWorker: () => ({
    headers: {
      Authorization: `Bearer ${authStore.token}`
    }
  })
})

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()

    if (!props.roomData?.id) {
      message.error('聊天室ID不存在')
      return
    }

    loading.value = true

    const updateData = {
      id: props.roomData.id,
      name: formData.name.trim(),
      description: formData.description.trim() || undefined,
      autoTalkEnabled: formData.autoTalkEnabled ? 1 : 0
    } as UpdateChatRoomRequest & { autoTalkEnabled: number }

    const response = await api.updateChatRoom(updateData)

    if (response.data?.code === 0) {
      message.success('聊天室更新成功')
      emit('success')
      handleCancel()
    } else {
      message.error(response.data?.message || '更新失败')
    }
  } catch (error) {
    console.error('更新聊天室失败:', error)
    message.error('更新失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
}
</script>

<style scoped>
.form-help {
  margin-top: 4px;
  font-size: 12px;
  color: #8c8c8c;
  line-height: 1.4;
}
</style>
